package cc.laop.controller;

import cc.laop.support.realm.CustomUsernamePasswordToken;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Child on 2017/7/8.
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory
            .getLogger(LoginController.class);

    @Autowired
    private Producer captchaProducer;

    @RequestMapping("login.do")
    @ResponseBody
    public Map<String, Object> login(String username, String password,
                                     String captcha) {
        Map<String, Object> returnMap = new HashMap<>();
        // shiro 登录验证
        CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(
                username, password, captcha);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            returnMap.put("result", -1);
            returnMap.put("message", e.getMessage());
            return returnMap;
        }
        returnMap.put("result", 0);
        return returnMap;
    }

    @RequestMapping("logout.do")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:index.jsp";
    }

    /**
     * 生成验证码图片
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("kaptcha.do")
    public ResponseEntity<byte[]> kaptcha() throws IOException {
        String capText = captchaProducer.createText();
        Session shiroSession = SecurityUtils.getSubject().getSession();
        shiroSession.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.add("Pragma", "no-cache");
        headers.setCacheControl(
                "no-store, no-cache, must-revalidate,post-check=0, pre-check=0");
        headers.setExpires(0);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpeg", os);
        return new ResponseEntity<byte[]>(os.toByteArray(), headers,
                HttpStatus.CREATED);
    }

}
